package jee.boot.encrypt.webInterceptor;

import jee.boot.encrypt.config.DataEncryptConfig;
import jee.boot.encrypt.config.IEncryptDecrypt;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Objects;

/**
 *  请求数据解密
 */
@ControllerAdvice(basePackages = "jee.boot")
public class WebRequestBodyAdvice implements RequestBodyAdvice {
    @Autowired
    private IEncryptDecrypt encryptDecrypt;
    @Autowired
    private DataEncryptConfig dataEncryptConfig;
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return body;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
           return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        if (dataEncryptConfig.getEnableEncryptedStorage()) {
            if (Objects.isNull(body)) {
                return null;
            }
            // 参数如果是数组,则循环进行解密
            if (body instanceof ArrayList) {
                ArrayList resultList = (ArrayList) body;
                if (CollectionUtils.isNotEmpty(resultList) && encryptDecrypt.needToDecrypt(resultList.get(0))) {
                    logger.debug("传输-拦截请求数据进行解密处理");
                    for (Object o : resultList) {
                        encryptDecrypt.decrypt(o);
                    }
                }
            } else {
                // 解密
                if (encryptDecrypt.needToDecrypt(body)) {
                    logger.debug("传输-拦截请求数据进行解密处理");
                    encryptDecrypt.decrypt(body);
                }
            }
        }
        return body;
    }


}